//
//  SNEquipmentScreenViewController.m
//  project
//
//  Created by 张淋 on 2019/5/7.
//  Copyright © 2019 黄建华. All rights reserved.
//

#import "SNEquipmentScreenViewController.h"
#import "JHFeilterManager.h"
#import "SNEquipmentScreenImageView.h"
#import "ZJSwitch.h"
#import "OTAShowView.h"

@interface SNEquipmentScreenViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic, strong)SNEquipmentScreenImageView *equipmentScreenSettingView;
@property (nonatomic, strong) OTAShowView *showView;
@property (nonatomic, strong) UIView *bgView;
@property (nonatomic, assign) BOOL isChangePhoto;
@property (nonatomic, assign) int stepHeight;
@property (nonatomic, assign) int timeHeight;

@end

@implementation SNEquipmentScreenViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = SNCOLORWHITE;
    
    if ([self getDocumentImage]) {
        _isChangePhoto = NO;
    } else {
        _isChangePhoto = YES;
    }
    
    _equipmentScreenSettingView = [[SNEquipmentScreenImageView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - FitSimpleIpx(20, 44))];
    [self.view addSubview:_equipmentScreenSettingView];
    
    // 获取屏保相关的按钮的状态
    [KK_BLESend sendGetDeviceIsCanSetScreenImage:^(id object, KKBLEAcceptType type) {
    }];
    
    weakSelf(weakSelf);
    _equipmentScreenSettingView.block = ^(id  _Nonnull sender) {
        strongSelf(strongSelf);
        if ([sender isKindOfClass:[UIButton class]]) {
            UIButton *btn = (UIButton *)sender;
            if (btn.tag == 100) {
                // 照相
                [strongSelf openMediaType:UIImagePickerControllerSourceTypeCamera];
            } else if (btn.tag == 200) {
                // 相册
                [strongSelf openMediaType:UIImagePickerControllerSourceTypePhotoLibrary];
            } else if (btn.tag == 300){
                [strongSelf.navigationController popViewControllerAnimated:YES];
            } else if (btn.tag == 400) {
                [strongSelf saveAction:btn];
            } else {
                
            }
        } else if ([sender isKindOfClass:[ZJSwitch class]]){
            ZJSwitch *zjswitch = (ZJSwitch *)sender;
            if (zjswitch.tag == 666) {
                // 是否显示步数
                strongSelf.equipmentScreenSettingView.screenView.stepImageView.hidden = !strongSelf.equipmentScreenSettingView.screenView.stepImageView.hidden;
                if (strongSelf.equipmentScreenSettingView.screenView.stepImageView.hidden) {
                    int stepH = strongSelf.equipmentScreenSettingView.screenView.frame.size.height - self.stepHeight;
                    [strongSelf.equipmentScreenSettingView.screenView setFrame:CGRectMake(strongSelf.equipmentScreenSettingView.screenView.frame.origin.x, strongSelf.equipmentScreenSettingView.screenView.frame.origin.y, strongSelf.equipmentScreenSettingView.screenView.frame.size.width, stepH)];
                } else {
                    strongSelf.equipmentScreenSettingView.screenView.stepImageView.tintColor = strongSelf.equipmentScreenSettingView.currentSelectButton.backgroundColor;//此时显示改变颜色后的图片
                    strongSelf.equipmentScreenSettingView.screenView.stepImageView.contentMode =  UIViewContentModeScaleAspectFit;
                    if (strongSelf.equipmentScreenSettingView.screenView.frame.origin.y > strongSelf.equipmentScreenSettingView.backImageView.frame.size.height - self.timeHeight - self.stepHeight) {
                        [strongSelf.equipmentScreenSettingView.screenView setFrame:CGRectMake(strongSelf.equipmentScreenSettingView.screenView.frame.origin.x, strongSelf.equipmentScreenSettingView.screenView.frame.origin.y - self.stepHeight, strongSelf.equipmentScreenSettingView.screenView.frame.size.width, strongSelf.equipmentScreenSettingView.screenView.frame.size.height + self.stepHeight)];
                    } else {
                        int stepH = strongSelf.equipmentScreenSettingView.screenView.frame.size.height + self.stepHeight;
                        [strongSelf.equipmentScreenSettingView.screenView setFrame:CGRectMake(strongSelf.equipmentScreenSettingView.screenView.frame.origin.x, strongSelf.equipmentScreenSettingView.screenView.frame.origin.y, strongSelf.equipmentScreenSettingView.screenView.frame.size.width, stepH)];
                    }
                }
            } else if (zjswitch.tag == 999) {
                strongSelf.equipmentScreenSettingView.bgView.hidden = !strongSelf.equipmentScreenSettingView.bgView.hidden;
//                [KK_BLESend sendScreenImageOpenState:zjswitch.on WithBlock:^(id object, KKBLEAcceptType type) {
//
//                }];
            }
        }
    };
    
    // 图片发送进度
    KK_BLESend.imageSendBlock = ^(NSInteger current, NSInteger all) {
        int value = 100.0*1.0*(current+1)/all;
        NSLog(@"发送进度>>>%d",value);
        [weakSelf.view addSubview:weakSelf.bgView];
        [weakSelf.showView.progressView setProgress:value / 99.9];
        weakSelf.showView.progressLabel.text = [NSString stringWithFormat:@"%d%@",value,@"%"];
        if (value == 100) {
            [weakSelf.bgView removeFromSuperview];
            weakSelf.isChangePhoto = NO;
        }
    };
    // 开启高速通道成功或者失败
    KK_BLESend.stateBlock = ^(NSInteger type) {
        
    };

    self.showView = [[OTAShowView alloc] initWithFrame:CGRectMake(0, 0, kSCREEN_WIDTH -80, 150)];
    [self.showView showViewProgress:SN_Text(@"数据传输中...")];
    self.showView.center = CGPointMake(kSCREEN_WIDTH/2, kSCREEN_HEIGHT/2);
    
    _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight)];
    _bgView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.4];
    [_bgView addSubview:self.showView];
}

- (void)saveAction:(UIButton *)sender {
    SHOWMBProgressHUD(SN_Text(@"保存中..."), nil, nil, nil, 2);
    if (KK_BLEModel.isConnected) {
        // 保存时间和步数所在的父视图的坐标
        int x = self.equipmentScreenSettingView.screenView.frame.origin.x;
        int y = self.equipmentScreenSettingView.screenView.frame.origin.y;
        NSDictionary *dic = @{@"x":[NSNumber numberWithInt:x],@"y":[NSNumber numberWithInt:y]};
        [[NSUserDefaults standardUserDefaults] setObject:dic forKey:@"ScreenViewXy"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        sender.enabled = NO;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            sender.enabled = YES;
        });
        // 1.发送屏保按钮状态
        [KK_BLESend sendScreenImageOpenState:_equipmentScreenSettingView.openSwitch.on WithBlock:^(id object, KKBLEAcceptType type) {
        }];
    } else {
         SHOWMBProgressHUD(nil, SN_Text(@"设备未连接"), nil, NO, 2.0);
    }
}

// 生成文件
- (void)makeImageFileWith:(UIImage *)image
{
    JHFeilterManager *manager   = [JHFeilterManager new];
    NSString         *imagePath = [manager createImageDataWithImage:image writetype:1];
    KK_BLESend.sendPath = imagePath;
    if (KK_BLEModel.isConnected && KK_BLESend.sendPath.length >0 && _isChangePhoto == YES) {
        [KK_BLESend sendImageData:YES WithBlock:^(id object, KKBLEAcceptType type) {
            
        }];
        [self performSelector:@selector(delayShowInfo1) withObject:nil afterDelay:1.0];
    }
    else
    {
        [self performSelector:@selector(delayShowInfo2) withObject:nil afterDelay:1.0];
    }
}

- (void)delayShowInfo1
{
    SHOWMBProgressHUD(SN_Text(@"开始发送图片"), nil, nil, NO, 1.0);
}

- (void)delayShowInfo2
{
    SHOWMBProgressHUD(SN_Text(@"蓝牙未连接或者没有选择图片"), nil, nil, NO, 1.0);
}

- (void)openMediaType:(UIImagePickerControllerSourceType)type {
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.sourceType = type;
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    [self presentViewController:imagePickerController animated:YES completion:nil];
    [self checkVideoStatus];
}

- (void)checkVideoStatus {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    switch (authStatus) {
            case AVAuthorizationStatusNotDetermined:
            //没有询问是否开启相机
            
            break;
            case AVAuthorizationStatusRestricted:
            //未授权，家长限制
            
            break;
            case AVAuthorizationStatusDenied:
        {
            //未授权
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:SN_Text(@"相机功能被禁止，是否开启？") message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            [alertController addAction:[UIAlertAction actionWithTitle:SN_Text(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                
            }]];
            
            [alertController addAction:[UIAlertAction actionWithTitle:SN_Text(@"退出") style:UIAlertActionStyleDefault handler:^(UIAlertAction *_Nonnull action) {
                
            }]];
            
            [alertController addAction:[UIAlertAction actionWithTitle:HHH_Text(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction *_Nonnull action) {
            }]];
            
            [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
            
            [self presentViewController:alertController animated:YES completion:nil];
        }
            break;
            case AVAuthorizationStatusAuthorized:
            //玩家授权
            
            break;
        default:
            break;
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info{
    _isChangePhoto = YES;
    UIImage *pickedImage = [info objectForKey:UIImagePickerControllerEditedImage];
    _equipmentScreenSettingView.backImageView.image = [UIImage imageCompressForSize:pickedImage targetSize:CGSizeMake(512, 512)];
    [self saveImageDocuments:[UIImage imageCompressForSize:pickedImage targetSize:CGSizeMake(240, 240)]];
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    NSLog(@"取消");
    _isChangePhoto = NO;
    [picker dismissViewControllerAnimated:YES completion:nil];
}


//保存图片
-(void)saveImageDocuments:(UIImage *)image{
    //拿到图片
    UIImage *imagesave = image;
    NSString *path_sandox = NSHomeDirectory();
    //设置一个图片的存储路径
    NSString *imagePath = [path_sandox stringByAppendingString:[NSString stringWithFormat:@"/Documents/%@.png",KK_BLEModel.bleMAC]];
    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
    [UIImagePNGRepresentation(imagesave) writeToFile:imagePath atomically:YES];
}

// 读取
-(UIImage *)getDocumentImage{
    // 读取沙盒路径图片
    NSString *aPath3=[NSString stringWithFormat:@"%@/Documents/%@.png",NSHomeDirectory(),KK_BLEModel.bleMAC];
    // 拿到沙盒路径图片
    UIImage *imgFromUrl3=[[UIImage alloc]initWithContentsOfFile:aPath3];
    // 图片保存相册
    return imgFromUrl3;
}

// 通知界面蓝牙状态
- (void)updateModel:(KKBLEModel *)model type:(KKBLEUpdateType)type
{
    
}

// 通知界面接收数据刷新相应界面的UI UpdateUiType
- (void)updateView:(KKBLEAcceptType)type
{
    // 获取屏保相关的按钮的状态回调
    if (type == BLTAcceptTypeDataScreenSaverInfo) {
        // 是否开启屏保功能
        if ([KK_BLEModel.bleScreenImagesSwitchState isEqualToString:@"1"]) {
            self.equipmentScreenSettingView.openSwitch.on =   YES;
            self.equipmentScreenSettingView.bgView.hidden = NO;
        } else if ([KK_BLEModel.bleScreenImagesSwitchState isEqualToString:@"2"]) {
            // 隐藏操作界面
            self.equipmentScreenSettingView.openSwitch.on =   NO;
            self.equipmentScreenSettingView.bgView.hidden = YES;
            [self.equipmentScreenSettingView.screenView setFrame:CGRectMake(131, self.equipmentScreenSettingView.screenView.frame.size.height -self.timeHeight - self.stepHeight , self.timeHeight * 5, self.timeHeight + self.stepHeight)];
        } else {
            
        }
        
        // 步数按钮的开关
        if ([KK_BLEModel.bleScreenStepSwitchState isEqualToString:@"1"]) {
            self.equipmentScreenSettingView.stepOpenSwitch.on = YES;
        } else if ([KK_BLEModel.bleScreenStepSwitchState isEqualToString:@"2"]) {
            self.equipmentScreenSettingView.stepOpenSwitch.on = NO;
        } else {
            
        }
        
        // 获取设备支持屏保的字体种类及对应分辨率
        [KK_BLESend sendGetDeviceScreenSaverFontInfo:^(id object, KKBLEAcceptType type) {
            
        }];
    } else if (type == BLTAcceptTypeDataScreenSaverFontType) {
        NSLog(@"屏保时间步数显示参数回调");
        // 获取字体的相关值
        NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"FontWidthHight"];
        int timeFontSize = [array[0] intValue];         // 16进制数
        int timeW = timeFontSize >> 8 & 0xff;               // 取高位为单个字体的宽  12:00 5个字
        int timeH = timeFontSize & 0xff;                    // 取低位为单个字体的高
        
        int stepFontSize = [array[1] intValue];         // 16进制数
        int stepW = stepFontSize >> 8 & 0xff;               // 取高位为单个字体的宽  00000 5个字
        int stepH = stepFontSize & 0xff;                    // 取低位为单个字体的高
        
        self.stepHeight = stepH;
        self.timeHeight = timeH;
        
        float x = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"ScreenViewXy"] objectForKey:@"x"] floatValue] ? [[[[NSUserDefaults standardUserDefaults] objectForKey:@"ScreenViewXy"] objectForKey:@"x"] floatValue] : 131;
        float y = [[[[NSUserDefaults standardUserDefaults] objectForKey:@"ScreenViewXy"] objectForKey:@"y"] floatValue]? [[[[NSUserDefaults standardUserDefaults] objectForKey:@"ScreenViewXy"] objectForKey:@"y"] floatValue] : 191;
        if ([KK_BLEModel.bleScreenStepSwitchState isEqualToString:@"1"]) {
            [self.equipmentScreenSettingView.screenView setFrame:CGRectMake(x, y, timeW * 5, stepH + timeH )];
        } else if ([KK_BLEModel.bleScreenStepSwitchState isEqualToString:@"2"]) {
            [self.equipmentScreenSettingView.screenView setFrame:CGRectMake(x, y, timeW * 5, timeH )];
        } else {
            
        }
        
        [self.equipmentScreenSettingView.screenView.timeImageView setFrame:CGRectMake(0, 0, timeW * 5, timeH)];
        [self.equipmentScreenSettingView.screenView.stepImageView setFrame:CGRectMake(timeW * 5 - stepW * 5 - stepW, self.equipmentScreenSettingView.screenView.timeImageView.bottom, stepW * 5 + 16, stepH )];
        
    } else if (type == BLTAcceptTypeDataScreenStepLocation) {
        // 步数设置成功
        NSLog(@"步数设置成功");
        if (_isChangePhoto) {
            // 发送图片
            [self makeImageFileWith:[self getDocumentImage]];
        }
        
    } else if (type == BLTAcceptTypeDataScreenTimeLocation) {
        NSLog(@"时间设置成功");
        // 3.发送是否显示步数按钮状态
        // 屏保时间位置  (133,191)
        // 屏保步数位置 （167，218）
        
        int x = self.equipmentScreenSettingView.screenView.frame.origin.x + (self.equipmentScreenSettingView.screenView.width - self.equipmentScreenSettingView.screenView.stepImageView.width);
        int y = self.equipmentScreenSettingView.screenView.frame.origin.y + self.equipmentScreenSettingView.screenView.timeImageView.height;
        
        [KK_BLESend sendSetIsShowStepSwitchState:self.equipmentScreenSettingView.stepOpenSwitch.on type:BLTScreenSendTypeStep fontColor:self.equipmentScreenSettingView.currentSelectButton.backgroundColor x:x y:y fontType:0 withBlock:^(id object, KKBLEAcceptType type) {
            
        }];
    } else if (type == BLTAcceptTypeDataScreenImageSwitchState) {
        if ([KK_BLEModel.bleScreenImagesSwitchState isEqualToString:@"1"]) {
            // 成功
            _equipmentScreenSettingView.openSwitch.on = YES;
            
            // 2.设置设备屏保显示时间的具体信息
            int x = self.equipmentScreenSettingView.screenView.frame.origin.x ;
            int y = self.equipmentScreenSettingView.screenView.frame.origin.y ;
            
            [KK_BLESend sendSetIsShowStepSwitchState:self.equipmentScreenSettingView.openSwitch.on type:BLTScreenSendTypeTime fontColor:self.equipmentScreenSettingView.currentSelectButton.backgroundColor x:x y:y fontType:1 withBlock:^(id object, KKBLEAcceptType type) {
                
            }];
            
         
        } else if ([KK_BLEModel.bleScreenImagesSwitchState isEqualToString:@"2"]) {
            // 关闭
            _equipmentScreenSettingView.openSwitch.on = NO;
        } else {
            
        }
    } else {
        
    }
    
    
}


@end
